<template>
  <div class="slide-up">
    <transition-group name="slide-up">
      <div v-for="(carGroup, i) of carList" :key="(i)" v-show="showIndex===i" class="car-group">
        <div class="car" v-for="car of carGroup" :key="car.id" :class="{ac: car.active}">{{car.plateNum}}{{car.k?`（${car.k}）`:''}}</div>
      </div>
    </transition-group>
  </div>
</template>

<script>
import Timer from './timer'
export default {
  props: {
    // 是否停止定时切换
    run: {
      type: Boolean,
      default: true
    },
    // 是否左右切换
    leftRun: {
      type: Boolean,
      default: false
    },
    carList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      showIndex: 0,
      total: 0
    }
  },
  computed: {
    allowRun () {
      return this.run && (this.leftRun || this.total > 1)
    }
  },
  watch: {
    run (run) {
      this.timer.stop()
      if (this.allowRun) {
        this.timer.start()
      }
    },
    carList () {
      this.update()
    }
  },
  created () {
    // 上下切换定时
    this.timer = new Timer({
      callBack: () => {
        let showIndex = this.showIndex
        showIndex++
        if (showIndex >= this.total) {
          if (this.leftRun) this.$emit('end')
          showIndex = 0
        }
        this.showIndex = showIndex
      },
      time: 5000
    })
  },
  mounted () {
    this.update()
  },
  destroyed () {
    this.timer.stop()
  },
  methods: {
    update () {
      this.total = this.carList.length
      if (this.allowRun) {
        this.timer.tryStart()
      } else {
        this.timer.stop()
      }
    }
  }
}
</script>

<style>
.slide-up {
  position: relative;
  height: 220px;
  overflow: hidden;
  color: #f00;
  font-size: 18px;
}
.car-group {
  transition: 0.4s ease;
  transition-property: opacity, transform;
  height: 220px;
  position: absolute;
  left: 0;
  top: 0;
  .car {
    padding: 10px 0;
  }
  .ac {
    color: #090;
  }
}

.slide-up-enter{
  opacity: 0;
  transform: translate3d(0, 200px, 0)!important;
}
.slide-up-leave-to {
  opacity: 0;
  transform: translate3d(0, -200px, 0);
}
</style>
